package gov.ccswj.modules.ccbusiness.integratedata;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Key;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import org.xidea.el.json.JSONDecoder;
import org.xidea.el.json.JSONEncoder;

import com.quantum.auth.RSA2048;

import gov.ccswj.common.utils.AuthUtils;
import gov.ccswj.common.utils.HttpRequest;
import gov.ccswj.modules.app.controller.AuthTest;
import gov.ccswj.modules.ccbusiness.entity.CRegisterinfoEntity;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JavaIdentifierTransformer;

public class IntegrateDate {

//	public static void main(String[] args) {
//		String resultdata = getCompanyData("getPatentInfo", "北京东方黑森林贸易有限公司",0);
//		getdate(resultdata);
//	}
	
	public static Map<Object, Object> getdate(String jsonStr) {
		JSONObject json = JSONObject.fromObject(jsonStr);
		JSONArray resultData = (JSONArray) json.get("RESULTDATA");
		
		JsonConfig config = new JsonConfig(); 
		config.setJavaIdentifierTransformer(new JavaIdentifierTransformer(){

			 @Override  
	         public String transformToJavaIdentifier(String str) {  
	                char[] chars = str.toCharArray();  
	                chars[0] = Character.toUpperCase(chars[0]); 
	                return new String(chars);  
	         }
		});
				

		Map<Object, Object> classMap = new HashMap<Object, Object>();
		for (Object jsonObject : resultData) {
			config.setRootClass(CRegisterinfoEntity.class);
			JSONObject jsonstr = JSONObject.fromObject(jsonObject);
			CRegisterinfoEntity cregisterinfo = (CRegisterinfoEntity) JSONObject.toBean(jsonstr,config);
			classMap.put("", cregisterinfo);
		}

		return classMap;
	}

	/**
	 * 获取企业信息
	 * 
	 * @param methodName
	 *            请求方法名称
	 * @param paramName
	 *            请求参数
	 *  pageno :  0, 输入参数 entname
	 *            1， 分页查询
	 *            2， rowkey查询
	 *         如果大于0 ，则有分页，默认查询1页，1000条数据
	 * @return 返回企业信息
	 */
	public static String getCompanyData(String methodName, String paramName,Integer pageno) {
		// TODO Auto-generated method stub
		try {
			String uid = "bcc9a8b6f5ea4047b3064da563c47dbd"; // 用户id
			String serviceUrl = "http://121.52.214.35/service";
			String serverName = methodName; // 服务方法名称

			// 服务相关参数的JSON数据
			Map<String, Object> conditoinMap = new HashMap<String, Object>();
			conditoinMap.put("uid", uid);
			conditoinMap.put("service", serverName);

			Map<String, Object> params = new HashMap<String, Object>();
			// params.put("keyword", "用友网络");
			// params.put("type", "0");
			
			if(pageno == 2){
				params.put("rowKey", paramName);
			}else{
				params.put("entName", paramName);
			}
			if(pageno == 4){
				params.put("reportDate", 2016);
			}
			if(pageno == 5){
				params.put("reportDate", 2015);
			}
			if(pageno ==3 ){
				params.put("dateParams", 2);
			}
			if(pageno == 1){
				params.put("pageNo", 1);
				params.put("pageSize", 10);
			}
			
			conditoinMap.put("params", params);
			String serverParams = JSONEncoder.encode(conditoinMap);

			// 参数加密
			String postParams = MessageFormat.format("uid={0}&data={1}", uid, getPostJsonStr(serverParams, uid));
			// 获取数据 String postParams = MessageF
			// 发送请求
			String result = HttpRequest.sendPost(serviceUrl, postParams);
			result = URLDecoder.decode(result, "UTF-8");
			// 转换数据
			// 参数解密
			Map<String, Object> resultMap = JSONDecoder.decode(result);
			String value = RasAndDesDecode(resultMap, uid);
			System.out.println(value);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 服务参数加密
	 *
	 * @param serverParams
	 * @return 返回加密后的密文
	 * @throws Exception
	 */
	private static String getPostJsonStr(String serverParams, String uid) throws Exception {
		Map<String, Object> authParams = AuthUtils.encode(serverParams, getKey(uid));
		return URLEncoder.encode(JSONEncoder.encode(authParams), "UTF-8");
	}

	/**
	 * 解密过程
	 *
	 * @param data
	 * @return
	 * @throws Exception
	 */
	private static String RasAndDesDecode(Map<String, Object> data, String uid) throws Exception {
		return AuthUtils.decode(data, getKey(uid));
	}

	/**
	 * 获取公钥
	 *
	 * @return
	 * @throws Exception
	 */
	private static Key getKey(String uid) throws Exception {
		String separator=System.getProperty("file.separator");
		Key key = null;
		try {
			URL url = AuthTest.class.getResource("/");
			//key = RSA2048.getKey(url.getPath().replace("api-fast.jar", "api-fast").replace("!", "") + "public_" + uid + ".key");// 密钥路径
			System.out.println(System.getProperty("user.dir"));
			key = RSA2048.getKey(System.getProperty("user.dir")+separator+"target"+separator+"classes"+separator+"" + "public_" + uid + ".key");// 密钥路径

			System.out.println("urlpath:"+url.getPath());
		} catch (Exception ex) {
			throw ex;
		}
		return key;
	}
	
	/**
     * 该方法是用于相同对象不同属性值的合并，如果两个相同对象中同一属性都有值，那么sourceBean中的值会覆盖tagetBean重点的值
     * @param sourceBean    被提取的对象bean
     * @param targetBean    用于合并的对象bean
     * @return targetBean,合并后的对象
     */
    public static Object combineSydwCore(Object sourceBean,Object targetBean){
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();
        
        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = sourceBeanClass.getDeclaredFields();
        for(int i=0; i<sourceFields.length; i++){
            Field sourceField = sourceFields[i]; 
            Field targetField = targetFields[i];  
            sourceField.setAccessible(true);
            targetField.setAccessible(true);
            try {
                if( !(sourceField.get(sourceBean) == null) &&  !"serialVersionUID".equals(sourceField.getName().toString())){
                    targetField.set(targetBean,sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return targetBean;
    }
    
    
    public static String getCompanyData1(String methodName, String paramName) {
        // TODO Auto-generated method stub
        try {
            String uid = "bcc9a8b6f5ea4047b3064da563c47dbd"; // 用户id
            String serviceUrl = "http://121.52.214.35/service";
            String serverName = methodName; // 服务方法名称

            // 服务相关参数的JSON数据
            Map<String, Object> conditoinMap = new HashMap<String, Object>();
            conditoinMap.put("uid", uid);
            conditoinMap.put("service", serverName);

            Map<String, Object> params = new HashMap<String, Object>();
            // params.put("keyword", "用友网络");
            // params.put("type", "0");
            params.put("entName", paramName);
            params.put("reportDate", "2017");
            
            conditoinMap.put("params", params);
            String serverParams = JSONEncoder.encode(conditoinMap);

            // 参数加密
            String postParams = MessageFormat.format("uid={0}&data={1}", uid, getPostJsonStr(serverParams, uid));
            // 获取数据 String postParams = MessageF
            // 发送请求
            String result = HttpRequest.sendPost(serviceUrl, postParams);
            result = URLDecoder.decode(result, "UTF-8");
            // 转换数据
            // 参数解密
            Map<String, Object> resultMap = JSONDecoder.decode(result);
            String value = RasAndDesDecode(resultMap, uid);
            System.out.println(value);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
    
    public static void main(String[] args) {
        String companyData1 = getCompanyData1("getEntAnnReportForGuaranteeInfo", "临沂市农丰食品有限公司");
        System.out.println(companyData1);
    }

}
